package com.jimmyhsu.ecnudaowei.coursetable.bulletin;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jimmyhsu.ecnudaowei.MyApplication;
import com.jimmyhsu.ecnudaowei.R;
import com.jimmyhsu.ecnudaowei.Utils.DownloadUtils;
import com.jimmyhsu.ecnudaowei.common.Config;
import com.jimmyhsu.ecnudaowei.common.views.GlideRoundTransform;
import com.jimmyhsu.ecnudaowei.secondhand.release.ReleaseNewItemActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public class AddBulletinActivity extends AppCompatActivity {

    private static final String EXTRA_COURSE_ID = "extra_course_id";
    private static final String EXTRA_B_ID = "extra_b_id";
    private static final String EXTRA_TITLE = "extra_title";
    private static final String EXTRA_CONTENT = "extra_content";
    private static final String EXTRA_IMAGE_URL = "extra_image_url";

    private static final int REQUEST_IMAGE = 1;
    @BindView(R.id.id_aab_title)
    EditText titleView;
    @BindView(R.id.id_aab_content)
    EditText contentView;
    @BindView(R.id.id_aab_remove_image)
    ImageButton removeImageButton;
    @BindView(R.id.id_aab_add_or_modify_image)
    ConstraintLayout addOrRemoveImageView;
    @BindView(R.id.id_aab_image)
    ImageView imageView;
    @BindView(R.id.id_aab_image_prompt)
    TextView imagePrompt;

    private String mImgPath;
    private String mTitle;
    private String mContent;
    private String mCourseId;
    private int mBId = -1;
    private boolean removeImage = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_bulletin);
        ButterKnife.bind(this);
        mCourseId = getIntent().getStringExtra(EXTRA_COURSE_ID);
        initContentIfNotNull();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("公告");
    }

    private void initContentIfNotNull() {
        Intent intent = getIntent();
        if (intent.getStringExtra(EXTRA_TITLE) != null) {
            mTitle = intent.getStringExtra(EXTRA_TITLE);
            mContent = intent.getStringExtra(EXTRA_CONTENT);
            titleView.setText(mTitle);
            contentView.setText(mContent);
            String url = intent.getStringExtra(EXTRA_IMAGE_URL);
            if (url.length() > 0) {
                Glide.with(this).load(Config.SERVER_URL + url).diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true)
                        .transform(new GlideRoundTransform(this, 4))
                        .into(imageView);
                removeImageButton.setVisibility(View.VISIBLE);
            }
            mBId = intent.getIntExtra(EXTRA_B_ID, -1);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem item = menu.add(0, 0, 0, "发布");
        item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case 0:
                if (checkInput()) {
                    uploadBulletin();
                }
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void uploadBulletin() {
        MyApplication app = MyApplication.getInstance(this);
        UploadBulletinService service = new Retrofit.Builder()
                .baseUrl(Config.SERVER_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build()
                .create(UploadBulletinService.class);
        Call<String> call = null;
        File file = null;
        MultipartBody.Part body = null;
        if (mImgPath != null) {
            file = new File(mImgPath);
            if (!file.exists()) {
                Snackbar.make(imageView, "图片不存在", Snackbar.LENGTH_SHORT).show();
                return;
            }
            RequestBody requestFile =
                    RequestBody.create(MediaType.parse("application/otcet-stream"), file);
            body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
        }
        if (mBId > 0) {
            if (mImgPath != null && mImgPath.length() > 0) {
                call = service.modifyBulletin(DownloadUtils.getFormRequestBody(mCourseId),
                        DownloadUtils.getFormRequestBody(String.valueOf(mBId)),
                        DownloadUtils.getFormRequestBody(app.getName()),
                        DownloadUtils.getFormRequestBody(app.getPassword()),
                        DownloadUtils.getFormRequestBody(String.valueOf(app.getId())),
                        DownloadUtils.getFormRequestBody(mTitle),
                        DownloadUtils.getFormRequestBody(mContent),
                        DownloadUtils.getFormRequestBody("true"),
                        DownloadUtils.getFormRequestBody("false"),
                        body);
            } else {
                call = service.modifyBulletin(mCourseId,
                        String.valueOf(mBId),
                        app.getName(),
                        app.getPassword(),
                        String.valueOf(app.getId()),
                        mTitle,
                        mContent,
                        "false",
                        removeImage ? "true" : "false");
            }
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    if (response.code() == 200) {
                        if ("success".equals(response.body())) {
                            Toast.makeText(AddBulletinActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                            BulletinActivity.startActivity(AddBulletinActivity.this, mCourseId);
                        } else if ("permission".equals(response.body())) {
                            Toast.makeText(AddBulletinActivity.this, "没有权限", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    Toast.makeText(AddBulletinActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            if (mImgPath != null) {
                call = service.uploadNewBulletin(DownloadUtils.getFormRequestBody(app.getName()),
                        DownloadUtils.getFormRequestBody(app.getPassword()),
                        DownloadUtils.getFormRequestBody(mCourseId),
                        DownloadUtils.getFormRequestBody(String.valueOf(app.getId())),
                        DownloadUtils.getFormRequestBody(mTitle),
                        DownloadUtils.getFormRequestBody(mContent),
                        DownloadUtils.getFormRequestBody("true"),
                        body);
            } else {
                call = service.uploadNewBulletin(app.getName(),
                        app.getPassword(),
                        mCourseId,
                        String.valueOf(app.getId()),
                        mTitle,
                        mContent,
                        "false");
            }
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    if (response.code() == 200) {
                        if (response.body() == null) {
                            Toast.makeText(AddBulletinActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                        } else if ("success".equals(response.body())) {
                            Toast.makeText(AddBulletinActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else if ("db insert failed".equals(response.body())) {
                            Toast.makeText(AddBulletinActivity.this, "数据库出错", Toast.LENGTH_SHORT).show();
                        } else if ("text length exceed".equals(response.body())) {
                            Toast.makeText(AddBulletinActivity.this, "字符数超限", Toast.LENGTH_SHORT).show();
                        } else if ("permission denied".equals(response.body())) {
                            Toast.makeText(AddBulletinActivity.this, "您不是管理员，无法发布公告", Toast.LENGTH_SHORT).show();
                        } else if ("file_error".equals(response.body())) {
                            Toast.makeText(AddBulletinActivity.this, "图片上传异常", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(AddBulletinActivity.this, "服务器异常：" + response.code(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    Toast.makeText(AddBulletinActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private boolean checkInput() {
        boolean result = true;
        mTitle = titleView.getText().toString();
        mContent = contentView.getText().toString();
        EditText focusView = null;
        if ("".equals(mTitle)) {
            focusView = titleView;
        }
        if ("".equals(mContent)) {
            focusView = contentView;
        }
        if (focusView != null) {
            result = false;
            focusView.setError("不得为空");
            focusView.requestFocus();
        }
        return result;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mImgPath != null) {
            File file = new File(mImgPath);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    @OnClick(R.id.id_aab_add_or_modify_image)
    void chooseImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @OnClick(R.id.id_aab_remove_image)
    void removeImage() {
        imageView.setImageResource(R.drawable.add);
        mImgPath = null;
        imagePrompt.setText("添加图片");
        removeImageButton.setVisibility(View.GONE);
        if (removeImage) {
            removeImage = false;
        } else {
            if (mBId >= 0) {
                removeImage = true;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_IMAGE) {
            Uri uri = data.getData();
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if (cursor == null) return;
            cursor.moveToFirst();
            mImgPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            ReleaseNewItemActivity.compressImage(this, mImgPath, 1);
            mImgPath = getFilesDir().getAbsolutePath() + "/temp1.jpg";
            Glide.with(this).load(new File(mImgPath)).diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .transform(new GlideRoundTransform(this, 4))
                    .into(imageView);
            removeImageButton.setVisibility(View.VISIBLE);
            imagePrompt.setText("更换图片");
            cursor.close();
        }
    }

    public static void startActivity(Context context, String courseId) {
        Intent intent = new Intent(context, AddBulletinActivity.class)
                .putExtra(EXTRA_COURSE_ID, courseId);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, String courseId, int bId, String title,
                                     String content, String imageUrl) {
        Intent intent = new Intent(context, AddBulletinActivity.class)
                .putExtra(EXTRA_COURSE_ID, courseId)
                .putExtra(EXTRA_B_ID, bId)
                .putExtra(EXTRA_TITLE, title)
                .putExtra(EXTRA_CONTENT, content)
                .putExtra(EXTRA_IMAGE_URL, imageUrl);
        context.startActivity(intent);
    }

    interface UploadBulletinService {

        @FormUrlEncoded
        @POST("phpprojects/course/releaseBulletin.php")
        Call<String> uploadNewBulletin(@Field("username") String username,
                                       @Field("password") String password,
                                       @Field("course_id") String courseId,
                                       @Field("author") String author,
                                       @Field("title") String title,
                                       @Field("content") String content,
                                       @Field("hasImage") String hasImage);

        @FormUrlEncoded
        @POST("phpprojects/course/editBulletin.php")
        Call<String> modifyBulletin(@Field("course_id") String courseId,
                                    @Field("b_id") String bId,
                                    @Field("username") String username,
                                    @Field("password") String password,
                                    @Field("author") String author,
                                    @Field("title") String title,
                                    @Field("content") String content,
                                    @Field("has_image") String hasImage,
                                    @Field("remove_image") String removeImage);

        @Multipart
        @POST("phpprojects/course/editBulletin.php")
        Call<String> modifyBulletin(@Part("course_id") RequestBody courseId,
                                    @Part("b_id") RequestBody bId,
                                    @Part("username") RequestBody username,
                                    @Part("password") RequestBody password,
                                    @Part("author") RequestBody author,
                                    @Part("title") RequestBody title,
                                    @Part("content") RequestBody content,
                                    @Part("has_image") RequestBody hasImage,
                                    @Part("remove_image") RequestBody removeImage,
                                    @Part MultipartBody.Part imageFile);

        @Multipart
        @POST("phpprojects/course/releaseBulletin.php")
        Call<String> uploadNewBulletin(@Part("username") RequestBody username,
                                       @Part("password") RequestBody password,
                                       @Part("course_id") RequestBody courseId,
                                       @Part("author") RequestBody author,
                                       @Part("title") RequestBody title,
                                       @Part("content") RequestBody content,
                                       @Part("hasImage") RequestBody hasImage,
                                       @Part MultipartBody.Part imageFile);


    }
}
